package org.example.service;

import io.netty.handler.codec.mqtt.MqttQoS;
import io.vertx.core.Vertx;
import io.vertx.mqtt.MqttClient;
import lombok.extern.slf4j.Slf4j;
import org.example.CommonMsg;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
@Slf4j
public class MQTTClient {

    @Value("${server.broadcast.ip}")
    private String ip = "127.0.0.1";

    @Value("${server.broadcast.port}")
    private int port = 1883;

    private MqttClient mqttClient;

    public  MQTTClient() {
        Vertx vertx = Vertx.vertx();
        mqttClient = MqttClient.create(vertx);
        mqttClient.connect(port, ip, res -> {
           if(res.succeeded()) {
              log.info("connect to mqtt bus[ip:{}, port:{}]", ip, port);
           }else {
               log.warn("【fail】connect to mqtt bus[ip:{}, port:{}]", ip, port);
             //  init();
           }
        }).exceptionHandler(throwable -> System.out.println("连接mqtt发生了异常。。。。。"));

    }

    public void publish(CommonMsg msg) {
        mqttClient.publish(String.valueOf(msg.getMsgDst()),
                msg.encodeToBuffer(),
                MqttQoS.AT_LEAST_ONCE,
                false,
                false);
    }
}
